from app.routers import auth_api, erp_api, tasks_api, dashboard_api, uniapp_goods_api, wangdian_api
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
# # from app.routers import auth_api, erp_api, tasks_api, dashboard_api, uniapp_goods_api, wangdian_apiniapp_goods_api, wangdian_apiniapp_goods_api, wangdian_apiniapp_goods_api, uniapp_goods_api
from app.controllers import goods_controller, user_controller, config_controller, sales_controller, address_controller
from app.controllers.role_controller import role_router, salesman_router, customer_router, order_router as proxy_order_router
from app.controllers.cart_controller import cart_router, address_router, stock_router, uniapp_cart_router
from app.controllers.order_controller import order_router, compat_order_router
from app.controllers.task_controller import task_router, compat_task_router
from app.controllers.statistics_controller import statistics_router
from app.controllers.frontend_statistics_controller import frontend_stats_router
from app.controllers.recommendation_controller import recommendation_router, uniapp_recommendation_router
from app.controllers.payment_controller import payment_router, uniapp_payment_router
from app.controllers.order_status_controller import status_router, uniapp_status_router
from fastapi.middleware.cors import CORSMiddleware
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from task.cleanup import (
    insert_update_goods,
    insert_update_goods_brand,
    backup_database,
    sync_stock_tasks,
    sync_refund_tasks,
    sync_order_tasks,
    sync_logistics_tasks,
    run_async_task,
    TASK_CONFIG
)
from task.base_info import (
    task_save_shop,
    task_save_logistics, 
    task_save_warehouse,
    task_save_provider,
    query_stockout_orders,
    query_logistics_sync,
    query_sales_trade,
    query_sales_api_trade
)
# 导入新的三层架构任务调度器
from task.task_scheduler import setup_new_scheduler, initialize_new_base_info
from app.controllers.upload_controller import router as upload_router

# app/main.py
app = FastAPI(title="FastAPI应用 - 三层架构重构版")

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 创建调度器
scheduler = AsyncIOScheduler()

# 包含各个路由 - 保留必要的老版本路由
# app.include_router(tasks_api.router)
# app.include_router(erp_api.router)
# # # app.include_router(auth_api.router  # 临时禁用)  # 临时禁用
# app.include_router(dashboard_api.router)

# 新增：使用三层架构的控制器（优先级更高的路由）
app.include_router(goods_controller.router, prefix="/uniapp")
app.include_router(user_controller.router, prefix="/uniapp")
app.include_router(config_controller.router, prefix="/uniapp")
app.include_router(sales_controller.router, prefix="/uniapp")
app.include_router(address_controller.router, prefix="/uniapp")

# 新增：角色管理相关路由
app.include_router(role_router, prefix="/uniapp")
app.include_router(salesman_router, prefix="/uniapp")
app.include_router(customer_router, prefix="/uniapp")
app.include_router(proxy_order_router, prefix="/uniapp")

# 新增：购物车相关路由
app.include_router(cart_router, prefix="/uniapp")
app.include_router(address_router, prefix="/uniapp")
app.include_router(stock_router, prefix="/uniapp")

# 新增：订单管理路由
app.include_router(order_router, prefix="/uniapp")

# 新增：任务管理路由
app.include_router(task_router, prefix="/uniapp")

# 新增：统计分析路由
app.include_router(statistics_router, prefix="/uniapp")

# 新增：前端兼容统计路由
app.include_router(frontend_stats_router, prefix="/uniapp")

# 新增：推荐系统路由
app.include_router(recommendation_router)
app.include_router(uniapp_recommendation_router)

# 新增：支付系统路由
app.include_router(payment_router)
app.include_router(uniapp_payment_router)

# 新增：订单状态管理路由
app.include_router(status_router)
app.include_router(uniapp_status_router)

# 新增：兼容路由
app.include_router(uniapp_cart_router)
app.include_router(compat_order_router)
app.include_router(compat_task_router)

# 保持必要的路由以确保向后兼容
app.include_router(uniapp_goods_api.router)
app.include_router(wangdian_api.router)

# 包含上传路由
app.include_router(upload_router)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 应用生命周期处理
@app.on_event("startup")
async def startup_event():
    print("应用启动中...")
    
    # 🔧 任务管理配置：设置为手动管理模式
    ENABLE_AUTO_TASKS = False  # 设置为False禁用自动任务调度
    
    if ENABLE_AUTO_TASKS:
        print("=== 启用自动任务调度 ===")
        # 选择使用哪种任务调度方式
        USE_NEW_TASK_ARCHITECTURE = True  # 设置为True使用新的三层架构任务调度
        
        if USE_NEW_TASK_ARCHITECTURE:
            print("=== 使用新的三层架构任务调度系统 ===")
            # 使用新的三层架构任务调度器
            setup_new_scheduler(scheduler)
            
            # 启动调度器
            scheduler.start()
            
            # 初始化基础信息同步（新版本）
            await initialize_new_base_info()
            
        else:
            print("=== 使用原有的任务调度系统 ===")
            # 保持原有的任务调度方式
            
            # 添加商品相关任务
            for task_name, config in TASK_CONFIG["goods_tasks"].items():
                task_func = globals()[task_name]
                scheduler.add_job(task_func, 'interval', **config)
            
            # 添加库存相关任务
            for task_name, config in TASK_CONFIG["stock_tasks"].items():
                scheduler.add_job(
                    run_async_task, 
                    'interval',
                    args=[globals()[task_name]],
                    **config
                )
            
            # 添加退款相关任务
            for task_name, config in TASK_CONFIG["refund_tasks"].items():
                scheduler.add_job(
                    run_async_task,
                    'interval',
                    args=[globals()[task_name]],
                    **config
                )
            
            # 添加维护任务
            # for task_name, config in TASK_CONFIG["maintenance_tasks"].items():
            #     task_func = globals()[task_name]
            #     scheduler.add_job(task_func, 'cron', **config)
            
            # 添加订单同步任务
            for task_name, config in TASK_CONFIG["order_tasks"].items():
                scheduler.add_job(
                    run_async_task,
                    'interval',
                    args=[globals()[task_name]],
                    **config
                )
            
            # 添加物流同步任务
            for task_name, config in TASK_CONFIG["logistics_tasks"].items():
                scheduler.add_job(
                    run_async_task,
                    'interval',
                    args=[globals()[task_name]],
                    **config
                )
            
            # 启动调度器
            scheduler.start()
            
            # 初始同步基础信息（原版本）
            await sync_base_info()
    else:
        print("🛑 === 任务手动管理模式 ===")
        print("📋 自动任务调度已禁用，任务只能通过 task_controller 手动执行")
        print("🔗 手动执行任务请访问: /uniapp/tasks/")
        print("💡 可用的手动任务:")
        print("   - POST /uniapp/tasks/execute (异步执行)")
        print("   - POST /uniapp/tasks/execute-sync (同步执行)")
        print("   - POST /uniapp/tasks/quick/goods-sync (快捷商品同步)")
        print("   - POST /uniapp/tasks/quick/stock-sync (快捷库存同步)")
        print("   - POST /uniapp/tasks/quick/order-sync (快捷订单同步)")
        print("   - POST /uniapp/tasks/quick/base-info-sync (快捷基础信息同步)")
        
        # 仍然创建调度器实例，但不添加任务，用于手动执行
        # 这样可以保证task_controller中的手动执行功能正常工作
        scheduler.start()  # 启动空的调度器

@app.on_event("shutdown")
async def shutdown_event():
    print("应用关闭中...")
    scheduler.shutdown()

async def sync_base_info():
    print("同步基础信息")
#     """同步基础信息"""
#     try:
#         # 同步店铺信息
#         await task_save_shop()
#         print("店铺信息同步完成")
        
#         # 同步物流信息
#         await task_save_logistics()
#         print("物流信息同步完成")
        
#         # 同步仓库信息
#         await task_save_warehouse()
#         print("仓库信息同步完成")
        
#         # 同步供应商信息
#         await task_save_provider()
#         print("供应商信息同步完成")

#            # 查询出库单
#         stockout_orders = await query_stockout_orders()
#         print("出库单数据:", stockout_orders)
        
#         # 查询物流信息
#         logistics_info = await query_logistics_sync()
#         print("物流信息:", logistics_info)
        
#         # 查询销售订单
#         sales_orders = await query_sales_trade()
#         print("销售订单:", sales_orders)
        
#         # 查询API销售订单
#         api_sales = await query_sales_api_trade()
#         print("API销售订单:", api_sales)
        
        
#     except Exception as e:
#         print(f"同步基础信息时出错: {e}")

# 在现有的main.py中添加健康检查端点
@app.get("/health")
async def health_check():
    return {"status": "healthy", "message": "服务运行正常"}

